import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'scrawl_painter.dart';
import 'file_utils.dart';
import 'dart:io';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/util/EncodeUtil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:jyofservice/util/UploadImageEvent.dart';
import 'package:jyofservice/util/Constants.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';


class PaintPage extends StatefulWidget {
  @override
  _PaintPageState createState() => _PaintPageState();
}

class _PaintPageState extends State<PaintPage> {

  final GlobalKey _repaintKey = new GlobalKey();
  List list = [];
  List pathList = [];

  static final List<Color> colors = [
    Colors.black,
    Colors.redAccent,
    Colors.lightBlueAccent,
    Colors.greenAccent,
  ];
  static final List<double> lineWidths = [5.0, 8.0, 10.0];
  File? imageFile;
  int selectedLine = 0;
  Color selectedColor = colors[0];
  List<Point> points = [Point(colors[0], lineWidths[0], [])];
  int curFrame = 0;
  bool isClear = false;

  double get strokeWidth => lineWidths[selectedLine];

  var _dateTime;

  bool _showLoading = false;

  @override
  void initState() {
    super.initState();

//    //获取保存的截图
//    getScreenShotFile().then((file) {
//      if (mounted) {
//                    setState(() {
//        imageFile = file;
//      });}
//    });

    _dateTime = new DateTime.now().toString().substring(0,19);

  }

  @override
  Widget build(BuildContext context) {

    List<Widget> childrens = [];
    final _loadingContainer = Container(

//        color: Colors.black12.withOpacity(0.6),
      child:   SpinKitFadingCircle(
        color: Colors.blue,
        size: 50.0,
      ),

    );

    final _mainConatiner = Scaffold(
        appBar: AppBar(
          title: Text("用户签名"),
        ),
        body: Container(
          color: Colors.black38,
          child: Column(
            children: <Widget>[
              Expanded(
                child: Container(
                  color: Colors.white,
                  margin: EdgeInsets.all(12.0),
                  child: RepaintBoundary(
                    key: _repaintKey,
                    child: Stack(

                      children: <Widget>[
                        Container(
                          
                          color: Colors.white,
                          child: Container(
                            alignment: Alignment.bottomRight,
                            margin: EdgeInsets.all(10),
                            width: double.infinity,
                            child: Text("${_dateTime.toString()}",style: TextStyle(color: Colors.black45),),
                          ),
                        ),
                        Positioned(
                          child: _buildCanvas(),
                          top: 0.0,
                          bottom: 0.0,
                          left: 0.0,
                          right: 0.0,
                        )
                      ],
                    ),
                  ),
                ),
              ),
              _buildBottom(),
            ],
          ),
        ));


    childrens.add(_mainConatiner);

    if(_showLoading) {

      childrens.add(_loadingContainer);
    }


    return Stack(

      children: childrens,

    );
  }

  Widget _buildCanvas() {
    return StatefulBuilder(builder: (context, state) {
      return CustomPaint(
        painter: ScrawlPainter(
          points: points,
          strokeColor: selectedColor,
          strokeWidth: strokeWidth,
          isClear: isClear,
        ),
        child: GestureDetector(
          onPanStart: (details) {
            // before painting, set color & strokeWidth.
            isClear = false;
            points[curFrame].color = selectedColor;
            points[curFrame].strokeWidth = strokeWidth;
          },
          onPanUpdate: (details) {
            RenderBox referenceBox = context.findRenderObject() as RenderBox;
            Offset localPosition =
                referenceBox.globalToLocal(details.globalPosition);
            state(() {
              points[curFrame].points.add(localPosition);
            });
          },
          onPanEnd: (details) {
            // preparing for next line painting.
            points.add(Point(selectedColor, strokeWidth, []));
            curFrame++;
          },
        ),
      );
    });
  }

  Widget _buildBottom() {
    return Container(
      color: Colors.white,
      padding:
          EdgeInsets.only(top: 15.0, bottom: ScreenUtil().bottomBarHeight + 10),
      child: StatefulBuilder(builder: (context, state) {
        return Column(
          children: <Widget>[
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  GestureDetector(
                    child: Icon(
                      Icons.brightness_1,
                      size: 10.0,
                      color: selectedLine == 0
                          ? Colors.black87
                          : Colors.grey.withOpacity(0.5),
                    ),
                    onTap: () {
                      state(() {
                        selectedLine = 0;
                      });
                    },
                  ),
                  GestureDetector(
                    child: Icon(
                      Icons.brightness_1,
                      size: 15.0,
                      color: selectedLine == 1
                          ? Colors.black87
                          : Colors.grey.withOpacity(0.5),
                    ),
                    onTap: () {
                      state(() {
                        selectedLine = 1;
                      });
                    },
                  ),
                  GestureDetector(
                    child: Icon(
                      Icons.brightness_1,
                      size: 20.0,
                      color: selectedLine == 2
                          ? Colors.black87
                          : Colors.grey.withOpacity(0.5),
                    ),
                    onTap: () {
                      state(() {
                        selectedLine = 2;
                      });
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      color: selectedColor == colors[0]
                          ? Colors.grey.withOpacity(0.2)
                          : Colors.transparent,
                      child: Icon(
                        Icons.create,
                        color: colors[0],
                      ),
                    ),
                    onTap: () {
                      state(() {
                        selectedColor = colors[0];
                      });
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      color: selectedColor == colors[1]
                          ? Colors.grey.withOpacity(0.2)
                          : Colors.transparent,
                      child: Icon(
                        Icons.create,
                        color: colors[1],
                      ),
                    ),
                    onTap: () {
                      state(() {
                        selectedColor = colors[1];
                      });
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      color: selectedColor == colors[2]
                          ? Colors.grey.withOpacity(0.2)
                          : Colors.transparent,
                      child: Icon(
                        Icons.create,
                        color: colors[2],
                      ),
                    ),
                    onTap: () {
                      state(() {
                        selectedColor = colors[2];
                      });
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      color: selectedColor == colors[3]
                          ? Colors.grey.withOpacity(0.2)
                          : Colors.transparent,
                      child: Icon(
                        Icons.create,
                        color: colors[3],
                      ),
                    ),
                    onTap: () {
                      state(() {
                        selectedColor = colors[3];
                      });
                    },
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 10.0,
            ),
            Container(
              child: Row(
                children: <Widget>[
                  SizedBox(width: 10.0,),
                  Expanded(
                    child:  TextButton(
                      style: ButtonStyle(
                        //背景颜色
                        backgroundColor: WidgetStateProperty.resolveWith((states) {
                          //设置按下时的背景颜色
                          // if (states.contains(MaterialState.pressed)) {
                          //   return Colors.blue[200];
                          // }
                          //默认使用背景颜色
                          return Colors.red;
                        }),
                      ),
                      onPressed: () {
                        if (mounted) {
                          setState(() {
                            reset();
                          });
                        }
                      },
                      child: Text(
                        '清除',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  SizedBox(width: 5.0,),
                  Expanded(
                    child: TextButton(
                      style: ButtonStyle(
                        //背景颜色
                        backgroundColor: WidgetStateProperty.resolveWith((states) {
                          //设置按下时的背景颜色
                          // if (states.contains(MaterialState.pressed)) {
                          //   return Colors.blue[200];
                          // }
                          //默认使用背景颜色
                          return Colors.blue;
                        }),
                      ),
                      onPressed: () {

                        _showLoading = true;

                        RenderRepaintBoundary boundary =
                            _repaintKey.currentContext!.findRenderObject() as RenderRepaintBoundary;

                        //保存图片
                        saveScreenShot(boundary, success: (data,urlStr) {
                          print("成功:$data");

                          //截取字符串作为图片命名
                          String? fileName = urlStr.substring(
                              6, urlStr.length - 4);
                          //图片转base64
                          String imagePath = data.toString();
                          print("imagePath==$imagePath");
                          // String imageBase64;
                          // EncodeUtil.image2Base64(imagePath).then((
                          //     data) {
                          //   imageBase64 = data; //data.replaceAll('+', "%2B");
                          //   print("imageBase64===$imageBase64");
                          //
                          //   var str = {
                          //     "FileName": "$fileName.png",
                          //     "Base64Str": "$imageBase64"
                          //   };
                          //
                          //   print("str===$str");
                          //   list.add(str);
                          //   pathList.add(urlStr);
                          //
                          //   uploadImageData(imagePath,list,pathList);
                          //
                          // });

                          Navigator.pop(context,imagePath);

                        }, fail: () {
                          //加提示框
                          Fluttertoast.showToast(msg: "图片保存失败");

                        });
                      },
                      child: Text(
                        '确认',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  SizedBox(width: 10.0,),
                ],
              ),
            )
          ],
        );
      }),
    );
  }

  //上传图片
  Future uploadImageData(imagePath,filedata,pathList) async {

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key":key,
      "filedata":filedata,
      "ClientType": "phone",
      "ClientKey": aesData
    };


    print("data===${filedata.length}${data.toString()}");
    print("data===${WebConfig().baseUrl + "Public/UploadFile"}");


    Response response = await Dio().post(WebConfig().baseUrl + "Public/UploadFile", data: data);

    print("response:${response.data}");

    if (response.data["Code"] == "200") {

      if (mounted) {
        setState(() {
          _showLoading = false;
        });
      }
      Fluttertoast.showToast(
        msg: "上传成功",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 2,
      );

      var result = response.data["Data"];

      Constants.eventBus.fire(UploadImageEvent(resultList: result,pathList: pathList));

      //image_Path图片地址 返回显示图片
      Navigator.pop(context,imagePath);

      print("result===$result");

    } else {

      if (mounted) {
        setState(() {
          _showLoading = false;
        });
      }

      Fluttertoast.showToast(
        msg: response.data["Data"]["Msg"].toString(),
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 2,
      );
    }

    return response.data;


  }

  void reset() {
    isClear = true;
    curFrame = 0;
    points.clear();
    points.add(Point(selectedColor, strokeWidth, []));
  }
}
